package jp.ne.ayamesoft.ayamevoicedialer;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.speech.RecognizerIntent;
import android.telephony.PhoneNumberUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

public class AyameVoiceDialerSetting extends Activity {

	final int INT_MEMBER_MAX = 20;
	final int MENU_NEW_MEMBER = 0;
	final int MENU_SELECT_CONTACTS = 1;
	final int MENU_ABOUT = 2;
	final int MENU_B_SELECT_CONTACT = 0;
	final int MENU_B_DELETE = 2;
	final int MENU_B_EDIT = 1;
	final int IC_VOICE_RECOGNITION_REQUEST = 0x1001;
	final int IC_CONTACTS_URI_REQUEST = 0x1002;
	Button button_add = null;
	Resources resources;
	String dbname_MemberList;
	SQLHelper_MemberList helper_MemberList;
	SQLiteDatabase member_db;
	CMemberData[] member_list = new CMemberData[INT_MEMBER_MAX];
	int act_cnt;
	int list_position = 0;
	int sel_position = 0;
	ArrayList<CMemberData> aryMemberList = new ArrayList<CMemberData>();
	private ListView listviewadapter = null;
	private LinearLayout linearlayout;
	private boolean check_edit = false;
	private Button button;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		AyameLOG.D("Setting onCreate");
		super.onCreate(savedInstanceState);

		for (int i = 0; i < INT_MEMBER_MAX; i++) {
			member_list[i] = new CMemberData();
		}
		setContentView(R.layout.main);

		listviewadapter = (ListView) findViewById(R.id.listview);
		linearlayout = (LinearLayout) findViewById(R.id.addmeber);
		button = (Button) findViewById(R.id.button_add);
		button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				New_Member();
			}
		});
		linearlayout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				New_Member();
			}
		});

	}

	@Override
	protected void onDestroy() {

		helper_MemberList.close();
		super.onDestroy();
	}

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {

			Bundle bundle = (Bundle) msg.obj;
			int position = bundle.getInt("a", -1);
			if (position != -1) {
				dialogcreat(position);
			}
			position = bundle.getInt("call", -1);
			if (position != -1) {
				String numberstring = bundle.getString("number");
				startSend(numberstring);
			}

		}
	};

	public void dialogcreat(final int _id) {

		sel_position = _id;
		CharSequence[] items = new CharSequence[3];
		;
		items[MENU_B_SELECT_CONTACT] = resources
				.getString(R.string.select_contact);
		items[MENU_B_DELETE] = resources.getString(R.string.delete);
		items[MENU_B_EDIT] = "Edit nickname";
		AlertDialog.Builder ad = new AlertDialog.Builder(this);
		ad.setTitle("Menu:[" + aryMemberList.get(_id).nickname + "]");
		ad.setCancelable(true);

		ad.setItems(items, new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				AyameLOG.D("selected id[" + String.valueOf(which) + "]");
				switch (which) {
				case MENU_B_SELECT_CONTACT:
					Select_Contact();
					break;
				case MENU_B_DELETE:
					helper_MemberList.Clear_all_By_id(member_db, aryMemberList
							.get(_id).id);
					onResume();
					break;
				case MENU_B_EDIT:
					check_edit = true;
					New_Member();
				}
			}
		});
		AlertDialog alert = ad.create();
		alert.show();

	}

	/*
	 * @Override protected void onListItemClick(ListView l, View v, final int
	 * position, long id) { AyameLOG.D("ItemClick position:" + position); //
	 * 
	 * id);
	 * 
	 * sel_position = position; CharSequence[] items = new CharSequence[2];
	 * items[MENU_B_SELECT_CONTACT] = resources
	 * .getString(R.string.select_contact) "Select Contact" ;
	 * items[MENU_B_DELETE] = resources.getString(R.string.delete) "Delete" ;
	 * AlertDialog.Builder ad = new AlertDialog.Builder(this);
	 * ad.setTitle("Menu:[" + aryMemberList.get(position).nickname + "]");
	 * ad.setCancelable(true);
	 * 
	 * ad.setItems(items, new DialogInterface.OnClickListener() {
	 * 
	 * public void onClick(DialogInterface dialog, int which) {
	 * AyameLOG.D("selected id[" + String.valueOf(which) + "]"); switch (which)
	 * { case MENU_B_SELECT_CONTACT: Select_Contact(); break; case
	 * MENU_B_DELETE: helper_MemberList.Clear_all_By_id(member_db, aryMemberList
	 * .get(position).id); onResume(); break; } } }); AlertDialog alert =
	 * ad.create(); alert.show(); }
	 */

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		menu.add(0, MENU_NEW_MEMBER, 0, R.string.new_member);
		// menu.add(0, MENU_SELECT_CONTACTS, 0, "Select Contacts");
		menu.add(0, MENU_ABOUT, 0, "About");
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		// 
		switch (item.getItemId()) {
		case MENU_NEW_MEMBER:
			AyameLOG.D("Menu position:MENU_NEW_MEMBER");
			New_Member();
			return true;

			/*
			 * case MENU_SELECT_CONTACTS:
			 * AyameLOG.D("Menu position:SELECT_CONTACTS"); Select_Contacts();
			 * return true;
			 */

		case MENU_ABOUT:
			AyameLOG.D("Menu position:MENU_ABOUT");
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	public void startSend(String number) {
		Intent intent = new Intent("android.intent.action.CALL", Uri
				.parse("tel:" + number));
		startActivity(intent);
		finish();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		// 
		super.onActivityResult(requestCode, resultCode, data);

		int match_cnt;
		if (requestCode == IC_VOICE_RECOGNITION_REQUEST
				&& resultCode == RESULT_OK) {

			final ArrayList<String> matches = data
					.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
			match_cnt = matches.size();
			AyameLOG.D("matches = [" + String.valueOf(match_cnt) + "]");

			if (match_cnt == 0) {
			} else {
				CharSequence[] items = new CharSequence[match_cnt];
				for (int i = 0; i < match_cnt; i++) {
					items[i] = matches.get(i);
				}
				AlertDialog.Builder ad = new AlertDialog.Builder(this);
				ad.setTitle(R.string.select_nickname);
				// ad.setMessage("メッセージ");
				ad.setCancelable(true);
				ad.setItems(items, new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						AyameLOG
								.D("selected id[" + String.valueOf(which) + "]");
						Add_Member(matches.get(which));
						onResume();
					}
				});
				AlertDialog alert = ad.create();
				alert.show();
			}
		} else if (requestCode == IC_CONTACTS_URI_REQUEST
				&& resultCode == RESULT_OK) {
			
			int dial_cnt = 0;
			final String[] dial_number = new String[5];
			final String reg_name;
			Uri result = data.getData();
			String id = result.getLastPathSegment();
			AyameLOG.D("id = [" + id + "]");
			Cursor c = getContentResolver().query(Phone.CONTENT_URI, null,
					Phone.CONTACT_ID + "=?", new String[] { id }, null);

			if (c.moveToFirst()) {
				
				reg_name = c.getString(c.getColumnIndex(Phone.DISPLAY_NAME));
				AyameLOG.D("contact name : " + reg_name);
				do {
					dial_number[dial_cnt] = PhoneNumberUtils
							.getStrippedReversed(c
									.getString(c
											.getColumnIndex(/* Phone.NUMBER */Phone.DATA4)));
					AyameLOG.D("dial_number : " + dial_number[dial_cnt]);
					dial_cnt++;
					if (dial_cnt >= 5) {
						break;
					}
				} while (c.moveToNext());
			} else {
				AyameLOG.D("no dial number!");
				return;
			}

			AyameLOG.D("dial_cnt : " + String.valueOf(dial_cnt));
			// AyameLOG.D("getcount : " + String.valueOf(c.getCount()));
			if (dial_cnt >= 2) {

				CharSequence[] items = new CharSequence[dial_cnt];
				for (int i = 0; i < dial_cnt; i++) {
					items[i] = dial_number[i];
				}
				AlertDialog.Builder ad = new AlertDialog.Builder(this);
				ad.setTitle(R.string.select_tel_number);
				ad.setCancelable(true);
				ad.setItems(items, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						AyameLOG
								.D("selected id[" + String.valueOf(which) + "]");
						Member_Registration(aryMemberList.get(sel_position).id,
								reg_name, dial_number[which]);
						onResume();
					}
				});
				AlertDialog alert = ad.create();
				alert.show();

			} else {
				Member_Registration(aryMemberList.get(sel_position).id,
						reg_name, dial_number[0]);
				onResume();
			}
		}
	}

	private void New_Member() {

		try {

			Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);

			intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
					RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);

			intent.putExtra(RecognizerIntent.EXTRA_PROMPT, resources
					.getString(R.string.speak_nickname));

			intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 20);

			startActivityForResult(intent, IC_VOICE_RECOGNITION_REQUEST);

		} catch (ActivityNotFoundException e) {

			Toast.makeText(this,
					resources.getString(R.string.not_support_voice_reg),
					Toast.LENGTH_LONG).show();

		}
	}

	private void Select_Contact() {
		Intent intent = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
		startActivityForResult(intent, IC_CONTACTS_URI_REQUEST);
	}

	private Cursor getCursorOfMemberList(SQLHelper_MemberList hdb) {
		return hdb.getReadableDatabase().query(hdb.STR_TABLE_NAME,
				new String[] { "id", "nickname", "name", "number", "atrb" },
				null, null, null, null, "id");
	}

	private void Add_Member(String new_nickname) {

		int empty_id = -1;
		for (int i = 0; i < INT_MEMBER_MAX; i++) {
			if (member_list[i].atrb == 0) {
				empty_id = member_list[i].id;
				AyameLOG.D("Setting empty_id:" + String.valueOf(empty_id));
				break;
			}
		}
		if (empty_id == -1) {
			return;
		}
		if (check_edit) {
			empty_id = sel_position;
			check_edit = false;
		}
		helper_MemberList.Update_all_By_id(member_db, empty_id, new_nickname,
				null, null, 1);

	}

	private void Member_Registration(int id, String name, String number) {

		helper_MemberList
				.Update_all_By_id(member_db, id, null, name, number, 1);

	}

	@Override
	protected void onPause() {

		AyameLOG.D("Setting onPause");
		super.onPause();
		/* list_position = getListView().getFirstVisiblePosition(); */
		AyameLOG.D("Setting list_position:" + String.valueOf(list_position));

	}

	@Override
	protected void onRestart() {

		AyameLOG.D("Setting onRestart");
		super.onRestart();
	}

	@Override
	protected void onResume() {

		AyameLOG.D("Setting onResume");

		super.onResume();
		resources = getResources();
		dbname_MemberList = resources.getString(R.string.dbname_memberlist);
		helper_MemberList = new SQLHelper_MemberList(this, dbname_MemberList,
				null);
		member_db = helper_MemberList.getWritableDatabase();
		CMemberData work_memberdata;
		int all_cnt;

		/* debug */
		/*
		 * helper_MemberList.Update_nickname_By_id(member_db, 0, "お試しの名前 abc");
		 * helper_MemberList.Update_atrb_By_id(member_db, 0, 1);
		 */
		/*
		 * helper_MemberList.Update_nickname_By_id(member_db, 2, "いばらき");
		 * helper_MemberList.Update_name_By_id(member_db, 2, "茨木　次郎");
		 * helper_MemberList.Update_number_By_id(member_db, 2, "0698765432");
		 * helper_MemberList.Update_atrb_By_id(member_db, 2, 1);
		 * helper_MemberList.Clear_atrb_By_id(member_db, 5);
		 */
		/**/

		aryMemberList.clear();
		Cursor cur = getCursorOfMemberList(helper_MemberList);
		act_cnt = 0;
		all_cnt = 0;
		boolean isEof = cur.moveToFirst();
		while (isEof) {

			int id = cur.getInt(0);
			String nickname = cur.getString(1);
			String name = cur.getString(2);
			String number = cur.getString(3);
			int atrb = cur.getInt(4);
			isEof = cur.moveToNext();
			member_list[all_cnt].id = id;
			member_list[all_cnt].nickname = nickname;
			member_list[all_cnt].name = name;
			member_list[all_cnt].atrb = atrb;
			all_cnt++;
			if ((atrb & 0x01) == 0) {
				continue;
			}
			work_memberdata = new CMemberData();
			work_memberdata.id = id;
			work_memberdata.nickname = nickname;
			work_memberdata.name = name;
			work_memberdata.number = number;
			work_memberdata.atrb = atrb;
			aryMemberList.add(work_memberdata);
			act_cnt++;
			AyameLOG.D("id:" + String.valueOf(id) + " nickname:" + nickname
					+ " name:" + name + " number:" + number + " atrb:"
					+ String.valueOf(atrb));
		}
		cur.close();
		CMemberListAdapter adapter = new CMemberListAdapter(
				getApplicationContext(), aryMemberList, mHandler);
		listviewadapter.setAdapter(adapter);

		// setListAdapter(adapter);
		/*
		 * if (list_position > 0 && list_position < adapter.getCount()) {
		 * getListView().setSelection(list_position); }
		 */

	}

}